package se.hrbustrc.hlgshopping.controller;

import com.alipay.api.AlipayApiException;
import se.hrbustrc.hlgshopping.entity.OrderInfo;
import se.hrbustrc.hlgshopping.service.OrderInfoService;
import se.hrbustrc.hlgshopping.utils.PayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import se.hrbustrc.hlgshopping.utils.Result;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

@RestController
@RequestMapping("/alipay")
public class AliPayController {
    @Autowired
    private PayUtil payUtil;

    @Autowired
    private OrderInfoService orderInfoService;

    // 用于存储订单号与订单ID的映射关系
    private static final Map<String, Long> orderNumToIdMap = new ConcurrentHashMap<>();


    // 修改为GET请求，通过查询参数传递订单ID
    @GetMapping("/pay")
    public void alipay(@RequestParam Long id,
                       HttpServletResponse response) throws AlipayApiException, IOException {
        // 生成订单号（支付宝的要求）
        String time = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String user = UUID.randomUUID().toString().replace("-", "").toUpperCase();
        String orderNum = time + user;

        System.out.println("创建支付订单，订单ID: " + id + ", 支付宝订单号: " + orderNum);

        // 存储订单号与订单ID的映射关系
        orderNumToIdMap.put(orderNum, id);

        // 获取订单信息
        OrderInfo order = orderInfoService.getOrder(id);
        float orderValue = order.getPaymoney().floatValue();

        // 调用封装好的方法（给支付宝接口发送请求）
        String form = payUtil.sendRequestToAlipay(orderNum, orderValue, order.getOrderno());

        // 将表单直接写入响应
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write(form);
        response.getWriter().flush();
        response.getWriter().close();
    }

    // 支付宝同步通知回调
    @GetMapping("/return")
    public String returnCallback(HttpServletRequest request) throws ParseException {
        System.out.println("收到支付宝同步回调通知");
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();

        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
            System.out.println("参数: " + name + " = " + valueStr);
        }

        // 验证签名
        boolean signVerified = payUtil.verifySignature(params);
        System.out.println("签名验证结果: " + signVerified);

        if (signVerified) {
            // 商户订单号
            String outTradeNo = params.get("out_trade_no");
            // 支付宝交易号
            String tradeNo = params.get("trade_no");
            // 交易状态
            String tradeStatus = params.get("trade_status");

            System.out.println("商户订单号: " + outTradeNo);
            System.out.println("交易状态: " + tradeStatus);

            if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)) {
                System.out.println("支付成功，准备更新订单状态");
                // 支付成功，更新订单状态
                // 根据订单号找到对应的订单ID并更新状态为2（待发货）
                Long orderId = orderNumToIdMap.get(outTradeNo);
                System.out.println("查找订单ID结果: " + orderId);
                if (orderId != null) {
                    Result result = orderInfoService.upOrderState(orderId, 2);
                    System.out.println("更新订单状态结果: " + result);
                } else {
                    System.out.println("未找到对应的订单ID");
                    // 尝试通过其他方式查找订单
                    OrderInfo order = orderInfoService.getOrderByNo(outTradeNo);
                    if (order != null) {
                        System.out.println("通过订单编号找到订单，ID: " + order.getId());
                        Result result = orderInfoService.upOrderState(order.getId(), 2);
                        System.out.println("更新订单状态结果: " + result);
                    } else {
                        System.out.println("通过订单编号也未找到订单");
                    }
                }
                return "redirect:http://localhost:8081/#/paysuccess?payResult=true";
            }
        }

        return "redirect:http://localhost:8081/#/paysuccess?payResult=false";
    }

    // 支付宝异步通知回调
    @PostMapping("/notify")
    public String notifyCallback(HttpServletRequest request) {
        System.out.println("收到支付宝异步回调通知");
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();

        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
            System.out.println("参数: " + name + " = " + valueStr);
        }

        // 验证签名
        boolean signVerified = payUtil.verifySignature(params);
        System.out.println("签名验证结果: " + signVerified);

        if (signVerified) {
            // 商户订单号
            String outTradeNo = params.get("out_trade_no");
            // 支付宝交易号
            String tradeNo = params.get("trade_no");
            // 交易状态
            String tradeStatus = params.get("trade_status");

            System.out.println("商户订单号: " + outTradeNo);
            System.out.println("交易状态: " + tradeStatus);

            if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)) {
                System.out.println("支付成功，准备更新订单状态");
                // 支付成功，更新订单状态
                // 根据订单号找到对应的订单ID并更新状态为2（待发货）
                Long orderId = orderNumToIdMap.get(outTradeNo);
                System.out.println("查找订单ID结果: " + orderId);
                if (orderId != null) {
                    Result result = orderInfoService.upOrderState(orderId, 2);
                    System.out.println("更新订单状态结果: " + result);
                } else {
                    System.out.println("未找到对应的订单ID");
                    // 尝试通过其他方式查找订单
                    OrderInfo order = orderInfoService.getOrderByNo(outTradeNo);
                    if (order != null) {
                        System.out.println("通过订单编号找到订单，ID: " + order.getId());
                        Result result = orderInfoService.upOrderState(order.getId(), 2);
                        System.out.println("更新订单状态结果: " + result);
                    } else {
                        System.out.println("通过订单编号也未找到订单");
                    }
                }

                // 这是最重要的业务逻辑处理
                return "success"; // 告诉支付宝已经处理成功
            }
        }

        return "failure";
    }
}